const SystemService = require("../services/systemService");
const BaseController = require("./baseController");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");

const userService = require("../services/userService");
const deptService = require("../services/deptService");

class SystemController extends BaseController {
  constructor() {
    debugger
    super(SystemService);
  }

  async encodePwd(ctx) {
    const { password } = ctx.request.body;
    if (!password) {
      ctx.body = {
        code: 400,
        message: "密码不能为空",
        success: false,
      };
      return;
    }

    // 模拟前端加密逻辑（这里使用 bcrypt 加密）
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(password, saltRounds);

    ctx.body = {
      code: 200,
      message: "密码加密成功",
      success: true,
      data: {
        encodedPwd: hashedPassword,
      },
    };
  }

  async login(ctx) {
    const { username, password } = ctx.request.body;

    const user = await userService.getUserByUsername(username);

    if (!user) {
      ctx.body = {
        code: 400,
        message: "用户不存在",
        success: false,
      };
      return;
    }

    // 验证前端加密的密码
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      ctx.body = {
        code: 400,
        message: "密码错误",
        success: false,
      };
      return;
    }

    const dept = await deptService.getById(user.deptId);

    // 通过jwt生成token
    const token = jwt.sign(
      {
        id: user.id,
        username: user.username,
        name: user.name,
        sex: user.sex,
        deptId: user.deptId,
        deptName: dept.deptName,
        deptFullId: dept.fullId,
        deptFullName: dept.fullDeptName,
      },
      process.env.JWT_SECRET || "default_secret",
      {
        expiresIn: process.env.JWT_EXPIRES_IN || "1h",
      }
    );

    ctx.body = {
      code: 200,
      message: "登录成功",
      success: true,
      data: {
        user: user,
        token: token,
      },
    };
  }

  async updatePwd(ctx) {
    const { oldPassword, newPassword } = ctx.request.body;
    const userId = ctx.state.user.id; // 假设从 JWT 中获取用户 ID

    // 获取用户信息
    const user = await userService.getById(userId);
    if (!user) {
      ctx.body = {
        code: 400,
        message: "用户不存在",
        success: false,
      };
      return;
    }

    // 验证旧密码
    const isMatch = await bcrypt.compare(oldPassword, user.password);
    if (!isMatch) {
      ctx.body = {
        code: 400,
        message: "旧密码错误",
        success: false,
      };
      return;
    }

    // 哈希新密码
    const hashedNewPassword = await bcrypt.hash(newPassword, 10);

    // 更新密码
    await userService.update({ password: hashedNewPassword, id: user.id }, ctx);

    ctx.body = {
      code: 200,
      message: "密码修改成功",
      success: true,
    };
  }

  async register(ctx) {
    const { username, password, name, sex, deptId } = ctx.request.body;

    // 检查用户是否已存在
    const existingUser = await userService.getUserByUsername(username);
    if (existingUser) {
      ctx.body = {
        code: 400,
        message: "用户名已存在",
        success: false,
      };
      return;
    }

    // 对前端加密的密码再做一次哈希
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建用户
    const newUser = await userService.add(
      {
        username,
        password: hashedPassword,
        name,
        sex,
        deptId,
      },
      ctx
    );

    ctx.body = {
      code: 200,
      message: "注册成功",
      success: true,
      data: newUser,
    };
  }

  async checkUsername(ctx) {
    
    const { username } = ctx.request.query;

    const existingUser = await userService.getUserByUsername(username);
    if (existingUser) {
      ctx.body = {
        code: 400,
        message: "用户名已存在",
        success: false,
      };
      return;
    }

    ctx.body = BaseController.setResponse(200, "用户名可用");
  }

  async getDepartments(ctx) {
    
    ctx.body = BaseController.setResponse(200, "获取成功", { data: [] });
  }
}

module.exports = new SystemController();
